<template>
  <div class="update-name">
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right='onConfirm'
    >
    </van-nav-bar>

    <div class="name-field-wrap">
      <van-field
        v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'
export default {
  name: 'UpdateName',
  components: {},
  props: {
    name: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      localName: this.name
    }
  },
  computed: {},
  watch: {},
  mounted () {},
  methods: {
    async onConfirm () {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true
      })
      try { // 当状态码为409时, 表示用户已存在
        await updateUserProfile({
          name: this.localName
        })
        this.$toast.success('保存成功')
        this.$emit('close')
        // 修改成功更新视图的方式
        //  1. 重新获取数据
        //  2. 单独前端更新字段(推荐)
        this.$emit('update-name', this.localName) // 方式1 可以使用v-model
      } catch (err) {
        if (err && err.response && err.response.status === 409) {
          this.$toast.fail('昵称已存在')
        }
      }
    }
  }
}

</script>
<style lang='less' scoped>
.name-field-wrap {
  padding: 10px;
}
</style>
